//
//  SearchViewController.m
//  suRead
//
//  Created by Kobe LI on 16/4/25.
//  Copyright © 2016年 bao. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchResultViewController.h"

#import <Masonry/Masonry.h>
#import "UIControl+Blocks.h"

#import "ServiceNews.h"
#import "NewsASRViewController.h"

@interface SearchViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *inputView;
@property (weak, nonatomic) IBOutlet UITextField *searchTF;

@property(nonatomic,strong)UIView   *tagsContainer;

@end

@implementation SearchViewController

- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)asrAction:(id)sender {
    [self.view endEditing:YES];
    __weak typeof(self) weakSelf = self;
    NewsASRViewController *controller = [[NewsASRViewController alloc] initWithNibName:@"NewsASRViewController" bundle:[NSBundle mainBundle]];
    [controller setHandle:^(NSString *result) {
        weakSelf.searchTF.text = result;
        [weakSelf textFieldShouldReturn:weakSelf.searchTF];
    }];
    controller.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self.view addSubview:controller.view];
    [controller.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(controller.view.superview);
    }];
    [self addChildViewController:controller];
    [controller didMoveToParentViewController:self];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField.text isEqualToString:@""]) {
        return NO;
    }
    
    UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
    SearchResultViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"SearchResultViewController"];
    controller.keyWord = textField.text;
    [self showViewController:controller sender:nil];
    
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.searchTF.returnKeyType=UIReturnKeySearch;
    self.searchTF.delegate=self;

    self.inputView.layer.cornerRadius = 22.0f;
    self.inputView.layer.masksToBounds = YES;

    [ServiceNews doFetchKeywords:^(id responseObject, NSString *message)
    {
        NSString *keys = (NSString *)responseObject;
        NSArray *array = [keys componentsSeparatedByString:@","];
        if (array && [array count] > 0) {
            [self initTagView:array];
        }
    }
                         failure:^(NSString *message) {
        
    }];
    
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf asrAction:nil];
    });
}


- (void)initTagView:(NSArray *)tags
{
    __weak typeof(self) weak_self = self;
    
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    
    self.tagsContainer = [UIView new];
    self.tagsContainer.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tagsContainer];
    
    [self.tagsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.tagsContainer.superview);
        make.right.equalTo(self.tagsContainer.superview);
        make.top.mas_equalTo(weak_self.inputView.mas_bottom).offset(15.0f);
    }];

    
    CGFloat tagDistance = 10.0f;
    CGFloat tagPadding  = 19.0f;
    CGFloat tagHeight   = 33.0f;
    CGFloat tagsContainerWidth = screenSize.width;
    UIFont  *tagFont    = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:14.0f];
    
    __block CGFloat currentX = 10;
    __block CGFloat currentY = 10;
    
    UIView *lastTagView = nil;
    
    for (int i=0; i<[tags count]; i++)
    {
        NSString *tagName = [tags objectAtIndex:i];
        CGSize size = [tagName sizeWithAttributes:@{NSFontAttributeName: tagFont}];
        
        UIButton *tagButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [tagButton addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
            UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
            SearchResultViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"SearchResultViewController"];
            controller.keyWord = tagName;
            [self showViewController:controller sender:nil];
        }];
        [tagButton setBackgroundColor:[UIColor whiteColor]];
        tagButton.layer.cornerRadius = 5.0f;
        tagButton.layer.masksToBounds = YES;
        [tagButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [tagButton setTitle:tagName forState:UIControlStateNormal];
        tagButton.titleLabel.font = tagFont;
        [self.tagsContainer addSubview:tagButton];
        
        [tagButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            //先判断当前行是否放的下
            CGFloat totalWidth = (currentX + tagPadding * 2 + size.width);
            
            if (totalWidth <= tagsContainerWidth) {  //放当前行
                make.left.equalTo(tagButton.superview).offset(currentX);
                make.top.equalTo(tagButton.superview).offset(currentY);
                make.size.mas_equalTo(CGSizeMake(tagPadding * 2 + size.width, tagHeight));
                
                currentX = totalWidth + tagDistance;
            }
            else {  //换行
                currentX = 10;
                currentY = currentY + tagHeight + tagDistance ;
                
                totalWidth = (currentX + tagPadding * 2 + size.width);
                
                if (totalWidth > tagsContainerWidth) {  //文字过长，限制宽度为屏幕的宽度
                    
                    make.left.equalTo(tagButton.superview).offset(currentX);
                    make.top.equalTo(tagButton.superview).offset(currentY);
                    make.size.mas_equalTo(CGSizeMake(totalWidth, tagHeight));
                    
                    currentX = totalWidth + tagDistance;
                }
                else
                {
                    
                    make.left.equalTo(tagButton.superview).offset(currentX);
                    make.top.equalTo(tagButton.superview).offset(currentY);
                    make.size.mas_equalTo(CGSizeMake(tagPadding * 2 + size.width, tagHeight));
                    
                    currentX = totalWidth + tagDistance;
                }
                
                
            }
            
        }];
        
        lastTagView = tagButton;
    }
    
    
    if (lastTagView) {
        [self.tagsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(currentY + tagDistance + tagHeight);
        }];
        
//        self.tagsHeight = (currentY + tagDistance + tagHeight + 15.0f);
    }
    else {
        [self.tagsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@0);
        }];
        
    }
 
}

@end
